<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\command;


use think\console\Input;
use think\console\Output;
use think\facade\Db;

class CommodityFraction extends BaseCommand
{
    protected function configure()
    {
        // 指令配置
        $this->setName('commodity_fraction')
            ->setDescription('计算商品的分数');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->setDb($input, $output);
    }

    protected function executeAction(Input $input, Output $output){
        $year = date('Y-01-01');
        $time = strtotime(date('Y-m-d'))/86400;
        $periods = floor($time/3);
        $select = Db::name('commodity_fraction')
            ->field('sum(visit) AS visit,sum(collect) AS collect,sum(sell) AS sell,commodity_id');
        if ($periods == 0) {
            $select = $select
                ->where('create_time', '>=', $year)
                ->where('time','in',[$periods*3-2,$periods*3-1,$periods*3]);
        }else {
            $select = $select
                ->where('create_time', '<', $year)
                ->where('time', 'in', [365, 364, 363]);
        }
        $select = $select
            ->group('commodity_id')
            ->select()
            ->toArray();
        foreach ($select AS $key => $value){
            Db::name('commodity')
                ->where('id',$value['commodity_id'])
                ->update(['fraction' => $this->getFraction($value)]);
        }
    }

    private function getFraction(array $value) : float {
        $fraction = $value['sell'] * 0.05 + $value['visit'] * 0.005 + $value['collect'] * 0.02;
        $fraction > 30 && $fraction = 30;
        return $fraction;
    }
}